package bean;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

@WebServlet(name = "ChangeName")
public class ChangeName extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        EntityManagerFactory entityManagerFactory=null;
        EntityManager em=null;
        boolean flag=true;


        try{

            entityManagerFactory= Persistence.createEntityManagerFactory("MyDSTest");

            em = entityManagerFactory.createEntityManager();

            Query query=em.createNativeQuery("select * from USER",User.class);
            List<User> list=query.getResultList();

            if (list != null) {
                Iterator<User> it = list.iterator();
                while (it.hasNext()) {
                    User temp = (User)it.next();
                    if(temp.getUsername().equals(name)||temp.getEmail().equals(email)) flag=false;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            em.close();
        }


        if(flag)
        {
            User user=(User)request.getSession().getAttribute("user");
            if(user!=null) user.setUsername(name);
            if(email!=null) user.setEmail(email);
            request.getSession().setAttribute("user",user);
            function.writeDgutToUser(user);
            response.sendRedirect("interface.jsp");
        }
        else
        {
            request.getSession().removeAttribute("user");
            response.sendRedirect("/error.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

}
